import re, time,json
import requests
# pip install PyExecJS
import execjs
import hashlib

class WeChatLogin():
    _unixs = int(time.time() * 100000)

    def __init__(self,useraget,username,pwd):
        self.username = username
        self.pwd = pwd
        self.useragent = useraget
        self.cookies_item = dict()
        self.redirect_url = None


    def md5(self,string):
        """返回字符串的md5哈希值"""
        hash_object = hashlib.md5()
        hash_object.update(string.encode("utf-8"))
        return hash_object.hexdigest()


    def get_ua_id(self):
        '''获取ua_id pvi si等三个参数'''
        start_url = "https://mp.weixin.qq.com/"
        cookies_item = dict()
        headers = {
            "Host": "mp.weixin.qq.com",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": self.useragent,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8"
        }
        response_ua = requests.get(url=start_url, headers=headers)

        # 获取其他参数
        JS = execjs.compile('''function getParams(c) {
                   return (c || "") + Math.round(2147483647 * (Math.random() || .5)) * + new Date % 1E10  // 获取10位unix时间戳
                }''')
        pgv_pvi = JS.call('getParams')
        pgv_si = JS.call('getParams', "s")
        ua_id = response_ua.cookies.get("ua_id", None)
        if not ua_id:
            return None
        else:
            cookies_item['pgv_pvi'] = pgv_pvi
            cookies_item['ua_id'] = ua_id
            cookies_item['pgv_si'] = pgv_si
            return cookies_item


    def init_token(self):
        """获取初始化token"""
        cookies_item = self.get_ua_id()
        if not cookies_item:
            print("获取ua_id失败")
            return None
        start_url = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin"
        headers = {
            "Host": "mp.weixin.qq.com",
            "Connection": "keep-alive",
            "Content-Length": "99",
            "Origin": "https://mp.weixin.qq.com",
            "X-Requested-With": "XMLHttpRequest",
            "User-Agent": self.useragent,
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept": "*/*",
            "Referer": "https://mp.weixin.qq.com/",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
        }
        querystring = {
            "userlang": "zh_CN",
            "redirect_url": "",
            "login_type": "3",
            "sessionid": self._unixs,
            "token": "",
            "lang": "zh_CN",
            "f": "json",
            "ajax": "1"
        }
        response = requests.post(url=start_url, headers=headers, data=querystring, cookies=self.cookies_item)
        response_data = response.json()
        print(response_data)
        if response_data.get("base_resp", None).get("err_msg", None) == "ok":
            print(response.cookies.get("uuid", None))
            cookies_item['uuid'] = response.cookies.get("uuid", None)
            return cookies_item
        else:
            return None


    def get_new_token(self):
        """重新获取cookie"""
        start_url = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin"
        headers = {
            "Host": "mp.weixin.qq.com",
            "Connection": "keep-alive",
            "Content-Length": "136",
            "Origin": "https://mp.weixin.qq.com",
            "X-Requested-With": "XMLHttpRequest",
            "User-Agent": self.useragent,
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept": "*/*",
            "Referer": "https://mp.weixin.qq.com/",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
        }
        querystring = {"username":self.username,
                       "pwd":self.md5(self.pwd),"imgcode":"","f":"json","userlang":"zh_CN","redirect_url":"","token":"","lang":"zh_CN","ajax":"1"}
        cookie_dict = self.init_token()
        if not cookie_dict:
            print("初始化uuid失败")
            return None
        response = requests.post(url=start_url,headers=headers,data=querystring,cookies=cookie_dict)
        print("登陆返回值",response.json())
        # '{'base_resp': {'err_msg': 'acct/password error', 'ret': 200023}}' 用户名密码出错的情况
        if response.json().get("base_resp",None).get("err_msg",None)!="ok":
            print("请求token失败")
            return None
        else:
            self.redirect_url = response.json().get("redirect_url",None)
            for k,v in response.cookies.items():
                cookie_dict[k] = v
            cookie_dict['noticeLoginFlag'] = 1
            return cookie_dict
if __name__ == '__main__':
    test = WeChatLogin(useraget="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",username="cs11@keyike.com.cn",pwd="keyike123")
    # print(test.get_ua_id())
    # print(test.init_token())
    print(test.get_new_token())
    print(test.redirect_url)